/***
 *                    _ooOoo_
 *                   o8888888o
 *                   88" . "88
 *                   (| -_- |)
 *                    O\ = /O
 *                ____/`---'\____
 *              .   ' \\| |// `.
 *               / \\||| : |||// \
 *             / _||||| -:- |||||- \
 *               | | \\\ - /// | |
 *             | \_| ''\---/'' | |
 *              \ .-\__ `-` ___/-. /
 *           ___`. .' /--.--\ `. . __
 *        ."" '< `.___\_<|>_/___.' >'"".
 *       | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *         \ \ `-. \_ __\ /__ _/ .-` / /
 * ======`-.____`-.___\_____/___.-`____.-'======
 *                    `=---='
 *
 * .............................................
 *          佛祖保佑             永无BUG
 */

import store from '../store/index'
import { UI } from './ui'
import { DATA } from './data'
import { NAV } from './navigation'
import { subButtery } from './methods'
'use strict';

// 初始画布状态
function initStage(mapInfo, FPS){
    var FPS = FPS || 25;
    var screenWidth = window.innerWidth || document.body.clientWidth || document.documentElement.clientWidth;
    var screenHeight = window.innerHeight || document.body.clientHeight || document.documentElement.clientHeight;
    var mapInfo = mapInfo || {
        width: screenWidth,
        height: screenHeight
    };
    var rMap = mapInfo.width / mapInfo.height;//比例
    var width = screenWidth;
    var height = screenHeight;
    if (screenWidth > screenHeight){
        width = screenHeight * rMap;
        height = screenHeight;
    }else{
        width = screenWidth;
        height = screenWidth / rMap;
    }


    var mapNavCanvas = document.createElement('canvas');
    mapNavCanvas.width = width;
    mapNavCanvas.height = height;
    $('#mapNavDiv').append(mapNavCanvas);
    //实例化画布对象
    var stage = new createjs.Stage(mapNavCanvas);
    
    //注册stage，画布的信息
    DATA.register('stage', {'stage': stage, 'width': width, 'height': height}, {});
    console.log(stage)
    stage.scaleX = 1;
    stage.scaleY = 1;
    stage.regX = 0;
    stage.regY = 0;

	createjs.Touch.enable(stage);//开启触摸，disable禁止触摸
    createjs.Ticker.setFPS(FPS);//一秒25帧

    /**
     * 拖拽移动画布
     * **/
    stage.enableMouseOver(10);//用到mouseover要加上这一句
    createjs.Touch.enable(stage);//移动端也支持点击移动事件，允许设备触控

    stage.mouseMoveOutside = true;//鼠标离开画布继续调用鼠标移动事件

    //点击地图，隐藏其他模态框
    stage.on("click", function (evt) {});

    stage.on("mousedown", function (evt) {
         if(store.state.disabledMoveMap){
             return
         }else{
             // keep a record on the offset between the mouse position and the container position. currentTarget will be the container that the event listener was added to:
            evt.currentTarget.offset = { x: this.x - evt.stageX, y: this.y - evt.stageY };
         }
    });
    stage.on("pressmove", function (evt) {
        if(store.state.disabledMoveMap){
            return
        }else{
            // Calculate the new X and Y based on the mouse new position plus the offset.
            evt.currentTarget.x = evt.stageX + evt.currentTarget.offset.x;
            evt.currentTarget.y = evt.stageY + evt.currentTarget.offset.y;
            // make sure to redraw the stage to show the change:
            stage.update();
        }
    });

    //刻度事件，实时监听变化
	createjs.Ticker.addEventListener('tick', function(){
        //更新，重新绘制画布
		stage.update();
    });
}



//初始化所有功能点
function main(){
    DATA.register('ros', null, {});//实例化ros
    DATA.register('topic', {}, {});//当前topic话题
    
    /**
     * 订阅地图信息
     * 绘制地图
     * **/
	DATA.register('mapMsg', null, {fnSet: UI.dispMap}); //地图信息，隐藏loading ros message for map or map_edit
    DATA.register('mapStage', null, {}); //地图容器 bitmap for map or map_edit

    DATA.register('mapScaleStage', null, {}); //通过定于地图信息，存放地图当前缩放状态 scale for map

    //绘制站点
    DATA.register('waypointsMsg', null, {fnSet: UI.dispWaypoints});//站点列表信息,绘制
    DATA.register('waypointsStage', null, {}); // 站点容器 containers added to stage

    //绘制轨迹
    DATA.register('trajectoriesMsg', null, {fnSet: UI.dispTrajectories});//轨迹信息

    //机器人在地图上的姿态信息
    DATA.register('robotPoseMsg', null, {fnSet: UI.dispRobot});
    DATA.register('robotPoseStage', null, {});

    //全局路径信息
    DATA.register('globalPlanMsg', null, {fnSet: UI.dispGlobalPlan});
    DATA.register('globalPlanStage', null, {});//全局路径stage
    
    //局部路径信息
    DATA.register('localPlanMsg', null, {fnSet: UI.dispLocalPlan});
    DATA.register('localPlanStage', null, {});//局部路径stage

    //轮廓信息
    DATA.register('footprintMsg', null, {fnSet: UI.dispFootprint});
    DATA.register('footprintStage', null, {});//轮廓状态

    //激光信息
    DATA.register('laserScanMsg', null, {fnSet: UI.dispLaserScan});
    DATA.register('laserScanStage', null, {});//激光状态

    //注册tfMsg信息，存放转换后的数据，如激光，轮廓
    DATA.register('tfMsg', {}, {});

    /**
     * 初始化地图、轮廓、激光等状态
     * 接受两个参数，topicName和状态
     * true就订阅，false就取消订阅
     * **/
    DATA.register('display', null, {fnSet: UI.display});

    /**
     * 订阅ros状态，赋给roseMode，根据rosMode判断地图的状态。新建/编辑/切换
     * **/
    DATA.register('rosMode', null, {fnSet: UI.rosModeHandle});

    //建图状态
    DATA.register('mappingStatus', null, {});

    //注册小车导航状态
    DATA.register('navCtrlStatus', null, {});
   
    //loading
    DATA.register('loading', null, {fnSet: UI.loading});
    
    var url = window.location.hostname;
    var websocketServer = 'ws://10.42.0.1:9090';
    // var websocketServer = 'ws://' + url + ':9090';

    //初始化地图状态
    initStage();
    DATA.loading = {
        key: 'init',
        info: '载入中'
    };

    // 初始化ros连接状态
    NAV.init(websocketServer);

    //订阅电量
    subButtery();

    //订阅ros所有状态
    NAV.subRosStatus();
    
    //提交查询地图话题
    setTimeout(() => {
        console.log('publish map select');
        NAV.pubCmdString(NAV.CmdEnum.MapSelect);  
    }, 500);

    //监听TFS
    NAV.listenTf();

    //订阅显示地图信息，打点，宽高
    NAV.dispMapAndWps(true);

    //订阅轨迹
    NAV.dispTrajectories();

    //显示机器人
    // setTimeout(() => {
        NAV.dispRobot();
    // }, 500);


    //获取全局路径
    NAV.dispGlobalPlan();
    //获取局部路径
    NAV.dispLocalPlan();
    //订阅轮廓
    NAV.dispFootprint();
    //订阅激光
    NAV.dispLaserScan();

    //订阅小车导航状态
    NAV.subNavCtrlStatus();
}

//首先进行加载
$(()=>{
    const that = this;
    //初始化所有功能
    main();
    var disps = {
        disp_map: store.state.showMap,//地图打开or隐藏
        disp_robotPose: store.state.showRobotLocation,//机器人位置打开/隐藏
        disp_laserScan: store.state.showLaser,//激光打开/隐藏
        disp_globalPlan: store.state.showGlobalPath,//全局路径打开/隐藏
        disp_localPlan: store.state.showLocalPath,//局部路径
        disp_footprint: store.state.showOutline,//轮廓
        //disp_waypoints: $('#disp-waypoints').val()
    }
    
    //根据地图、机器人，激光、路径等初始化是否打开来显示
    for (var key in disps){
        var name = key.split('_')[1];
        var val = disps[key];
        //对应的所有功能显示/隐藏状态
        DATA.display = {
            property: name,
            value: val
        }
    }
});